<template>
  <div class="upload-box w-full h-full overflow-hidden">
    <a-upload
      draggable
      action="/"
      :custom-request="customRequest"
      :show-file-list="false"
      :accept="accept"
    >
      <template #upload-button>
        <slot name="tips"></slot>
      </template>
    </a-upload>
    <a-progress v-if="schedule && props.show" :percent="schedule" :style="{ width: '50%' }" />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { GetFileChunkWithSHA256, UploadChunk } from '@/util/new_file';
import type { RequestOption, UploadRequest } from '@arco-design/web-vue';
import * as api from '@/api/newfile/file';
import { Message } from '@arco-design/web-vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  single: {
    type: Boolean,
    default: false
  },
  startUpload: {
    type: String,
    default: ''
  },
  uploadPath: {
    type: String,
    default: ''
  },
  mergePath: {
    type: String,
    default: ''
  },
  accept: {
    type: String,
    default: ''
  },
  fileNameKey: {
    type: String,
    default: 'fileName'
  },
  filePathKey: {
    type: String,
    default: 'url'
  },
  show: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:modelValue', 'fileList']);
const uploadRes = ref<string>(props.modelValue);

const schedule = ref(0);
const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB

watch(
  () => props.modelValue,
  (val) => {
    uploadRes.value = val;
  }
);
const customRequest: any = async (option: RequestOption): Promise<UploadRequest> => {
  // 获取文件上传组件选中的文件
  const { fileItem } = option;
  // 对文件进行处理(分片)
  const data = await GetFileChunkWithSHA256(fileItem.file!, CHUNK_SIZE, schedule);
  schedule.value = 0.01;
  // 上传并合并文件
  await UploadChunk({
    startUpload: api.getStatrFunc(props.startUpload),
    uploadFunc: api.getUploadFunc(props.uploadPath),
    mergeFunc: api.getMergeFunc(props.mergePath),
    fileDataInfo: data,
    processVal: schedule
  }).then((res) => {
    // 需要的 file_sha256
    const { code, message, data } = res as any;
    if (code == 200) {
      // const rs = uploadRes.value.split('');
      const big = data.file_sha256;
      // 是否是单文件上传
      // rs.push(big);
      uploadRes.value = big;
      console.log(uploadRes.value);
      emits('fileList', [
        {
          [props.fileNameKey]: fileItem.file!.name,
          [props.filePathKey]: fileItem.file!.lastModified
        }
      ]);
      emits('update:modelValue', uploadRes.value);
      // setTimeout(() => {
      //   schedule.value = 0;
      // }, 500);
      return;
    }
    Message.error(`上传失败[${message}]`);
  });
  return {
    abort() {}
  };
};
</script>

<style lang="less" scoped></style>
